package study.datastructure.stack;

import study.datastructure.stack.Stack;

import java.util.Iterator;
import java.util.NoSuchElementException;

public class LinkedListStack<E> implements Stack<E>, Iterable<E> {

    // 栈节点类
    private  class Node {
        E data;
        Node next;

        Node(E data) {
            this.data = data;
        }
    }

    private Node top;   // 指向栈顶的节点
    private int size;   // 栈的元素个数
    private int capacity; // 栈的容量

    // 构造函数
    public LinkedListStack(int capacity) {
        this.capacity = capacity;
        this.size = 0;
        this.top = null;
    }

    @Override
    public void push(E item) {
        if (isFull()) {
            throw new IllegalStateException("Stack is full");
        }
        Node newNode = new Node(item);
        newNode.next = top;
        top = newNode;
        size++;
    }

    @Override
    public E pop() {
        if (isEmpty()) {
            throw new NoSuchElementException("Stack is empty");
        }
        E item = top.data;
        top = top.next;
        size--;
        return item;
    }

    @Override
    public E peek() {
        if (isEmpty()) {
            throw new NoSuchElementException("Stack is empty");
        }
        return top.data;
    }

    @Override
    public boolean isFull() {
        return size == capacity;
    }

    @Override
    public boolean isEmpty() {
        return top == null;
    }

    @Override
    public Iterator<E> iterator() {
        return new StackIterator();
    }

    // 内部类实现栈的迭代器
    private class StackIterator implements Iterator<E> {
        private Node current = top;

        @Override
        public boolean hasNext() {
            return current != null;
        }

        @Override
        public E next() {
            if (!hasNext()) {
                throw new NoSuchElementException();
            }
            E item = current.data;
            current = current.next;
            return item;
        }
    }

    // 返回栈的大小
    public int size() {
        return size;
    }

    public static void main(String[] args) {
        LinkedListStack<Integer> stack = new LinkedListStack<>(5);

        stack.push(10);
        stack.push(20);
        stack.push(30);

        System.out.println("栈顶元素: " + stack.peek()); // 输出: 栈顶元素: 30
        System.out.println("栈的大小: " + stack.size()); // 输出: 栈的大小: 3

        System.out.println("遍历栈元素:");
        for (int item : stack) {
            System.out.println(item);  // 输出: 30, 20, 10
        }

        stack.pop();
        System.out.println("弹出后栈顶元素: " + stack.peek()); // 输出: 栈顶元素: 20
    }
}
